﻿#region Licence
// <copyright file="Core/BaseDataService.cs" company="Kopigi">
// Copyright © Kopigi 2014
// </copyright>
// ****************************************************************************
// <author>Marc PLESSIS</author>
// <date>11/10/2014</date>
// <project>Nentang.wpf</project>
// <web>http://nentang.codeplex.com</web>
// <license>
// The MIT License (MIT)
// 
// Copyright (c) 2013 Marc Plessis
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
// </license>
#endregion
#region using

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using Database.DAL;
using Database.POCO.Base;
using GalaSoft.MvvmLight.Ioc;
using Interfaces;
using Interfaces.Enums;

#endregion

namespace Core.Services
{
    public abstract class BaseDataService : IDatabase
    {

        public IServiceNotification NotificationService
        {
            get { return SimpleIoc.Default.GetInstance<IServiceNotification>(); }
        }

        public abstract bool IsOffline { get; }

        private Dictionary<string, dynamic> _providers = new Dictionary<string, dynamic>(); 
        
        public void Add<T>(T entity) where T : BaseEntity
        {
            if (_providers.ContainsKey(typeof(T).ToString()))
            {
                dynamic provider;
                if (_providers.TryGetValue(typeof (T).ToString(), out provider))
                {
                    ((GenericProvider<T>)provider).Add(entity);
                }
            }
            else
            {
                var provider = new GenericProvider<T>(IsOffline);
                provider.Add(entity);
                _providers.Add(typeof(T).ToString(), provider);
                   
            }
        }

        public bool Any<T>(Expression<Func<T, bool>> predicate) where T : BaseEntity
        {
            if (_providers.ContainsKey(typeof(T).ToString()))
            {
                dynamic provider;
                if (_providers.TryGetValue(typeof(T).ToString(), out provider))
                {
                    return ((GenericProvider<T>)provider).Any(predicate);
                }
                return false;
            }
            else
            {
                var provider = new GenericProvider<T>(IsOffline);
                _providers.Add(typeof(T).ToString(), provider);
                return provider.Any(predicate);
            }
        }

        public bool Any<T>() where T : BaseEntity
        {
            if (_providers.ContainsKey(typeof(T).ToString()))
            {
                dynamic provider;
                if (_providers.TryGetValue(typeof(T).ToString(), out provider))
                {
                    return ((GenericProvider<T>)provider).Any();
                }
                return false;
            }
            else
            {
                var provider = new GenericProvider<T>(IsOffline);
                if (!_providers.ContainsKey(typeof(T).ToString()))
                {
                    _providers.Add(typeof(T).ToString(), provider);    
                }
                return provider.Any();
            }
        }

        public void Attach<T>(T entity) where T : BaseEntity
        {
            if (_providers.ContainsKey(typeof(T).ToString()))
            {
                dynamic provider;
                if (_providers.TryGetValue(typeof(T).ToString(), out provider))
                {
                    ((GenericProvider<T>)provider).Attach(entity);
                }
            }
            else
            {
                var provider = new GenericProvider<T>(IsOffline);
                provider.Attach(entity);
                _providers.Add(typeof(T).ToString(), provider);
            }
        }

        public Int64 Count<T>() where T : BaseEntity
        {
            if (_providers.ContainsKey(typeof (T).ToString()))
            {
                dynamic provider;
                if (_providers.TryGetValue(typeof (T).ToString(), out provider))
                {
                    return ((GenericProvider<T>) provider).Count();
                }
                return 0;
            }
            else
            {
                var provider = new GenericProvider<T>(IsOffline);
                _providers.Add(typeof(T).ToString(), provider);
                return provider.Count();
            }
        }

        public void Delete<T>(T entity, bool save = false) where T : BaseEntity
        {
            if (_providers.ContainsKey(typeof(T).ToString()))
            {
                dynamic provider;
                if (_providers.TryGetValue(typeof(T).ToString(), out provider))
                {
                    ((GenericProvider<T>)provider).Delete(entity);
                }
            }
            else
            {
                var provider = new GenericProvider<T>(IsOffline);
                provider.Delete(entity);
                _providers.Add(typeof(T).ToString(), provider);
            }

            if (save)
            {
                SaveChanges<T>();
            }
        }

        public void Delete<T>(Expression<Func<T, bool>> predicate, bool save = false) where T : BaseEntity
        {
            if (_providers.ContainsKey(typeof (T).ToString()))
            {
                dynamic provider;
                if (_providers.TryGetValue(typeof (T).ToString(), out provider))
                {
                    ((GenericProvider<T>) provider).Delete(predicate);
                }
            }
            else
            {
                var provider = new GenericProvider<T>(IsOffline);
                _providers.Add(typeof(T).ToString(), provider);
                provider.Delete(predicate);
            }

            if (save)
            {
                SaveChanges<T>();
            }
        }

        public void DeleteAll<T>(bool save = false) where T : BaseEntity
        {
            if (_providers.ContainsKey(typeof (T).ToString()))
            {
                dynamic provider;
                if (_providers.TryGetValue(typeof (T).ToString(), out provider))
                {
                    ((GenericProvider<T>) provider).DeleteAll();
                }
            }
            else
            {
                var provider = new GenericProvider<T>(IsOffline);
                _providers.Add(typeof(T).ToString(), provider);
                provider.DeleteAll();
            }

            if (save)
            {
                SaveChanges<T>();
            }
        }

        public void DetectChanges<T>() where T : BaseEntity
        {
            if (_providers.ContainsKey(typeof(T).ToString()))
            {
                dynamic provider;
                if (_providers.TryGetValue(typeof(T).ToString(), out provider))
                {
                    ((GenericProvider<T>)provider).DetectChanges();
                }
            }
            else
            {
                var provider = new GenericProvider<T>(IsOffline);
                _providers.Add(typeof(T).ToString(), provider);
                provider.DetectChanges();
            }
        }

        public IQueryable<T> Fetch<T>() where T : BaseEntity
        {
            if (_providers.ContainsKey(typeof (T).ToString()))
            {
                dynamic provider;
                if (_providers.TryGetValue(typeof (T).ToString(), out provider))
                {
                    return ((GenericProvider<T>) provider).Fetch();
                }
                return null;
            }
            else
            {
                var provider = new GenericProvider<T>(IsOffline); 
                _providers.Add(typeof(T).ToString(), provider);
                return provider.Fetch();
            }
        }

        public T First<T>(Expression<Func<T, bool>> predicate, bool newContext = false) where T : BaseEntity
        {
            if (_providers.ContainsKey(typeof (T).ToString()) && !newContext)
            {
                dynamic provider;
                if (_providers.TryGetValue(typeof (T).ToString(), out provider))
                {
                    return ((GenericProvider<T>) provider).First(predicate);
                }
                return null;
            }
            else
            {
                var provider = new GenericProvider<T>(IsOffline, newContext);
                if (!newContext)
                {
                    _providers.Remove(typeof (T).ToString());
                    _providers.Add(typeof (T).ToString(), provider);
                }
                return provider.First(predicate);
            }
        }

        public IEnumerable<T> GetAll<T>(bool newContext = false) where T : BaseEntity
        {
            if (_providers.ContainsKey(typeof (T).ToString()) && !newContext)
            {
                dynamic provider;
                if (_providers.TryGetValue(typeof (T).ToString(), out provider))
                {
                    return ((GenericProvider<T>) provider).GetAll().ToList();
                }
                return null;
            }
            else
            {
                var provider = new GenericProvider<T>(IsOffline, newContext);
                if (!newContext)
                {
                    _providers.Remove(typeof (T).ToString());
                    _providers.Add(typeof (T).ToString(), provider);
                }
                return provider.GetAll().ToList();
            }
        }

        public T GetById<T>(Int64 id, bool newContext = false)where T : BaseEntity
        {
            if (_providers.ContainsKey(typeof(T).ToString()) && !newContext)
            {
                dynamic provider;
                if (_providers.TryGetValue(typeof (T).ToString(), out provider))
                {
                    return ((GenericProvider<T>) provider).GetById(id);
                }
                return null;
            }
            else
            {
                var provider = new GenericProvider<T>(IsOffline, newContext);
                if (!newContext)
                {
                    _providers.Remove(typeof (T).ToString());
                    _providers.Add(typeof (T).ToString(), provider);
                }
                return provider.GetById(id);
            }
        }

        public bool IsNew<T>(T entity) where T : BaseEntity
        {
            if (_providers.ContainsKey(typeof (T).ToString()))
            {
                dynamic provider;
                if (_providers.TryGetValue(typeof (T).ToString(), out provider))
                {
                    return ((GenericProvider<T>) provider).IsNew(entity);
                }
                return false;
            }
            else
            {
                var provider = new GenericProvider<T>(IsOffline);
                _providers.Add(typeof(T).ToString(), provider);
                return provider.IsNew(entity);
            }
        }

        public T Save<T>(T entity, bool logEvent = false, string logMessage = "", ValueNotificationEnum logNotification = ValueNotificationEnum.None, bool saveChanges = true, bool detectChanges = true) where T : BaseEntity
        {
            T objReturn;
            if (_providers.ContainsKey(typeof(T).ToString()))
            {
                dynamic provider;
                objReturn = _providers.TryGetValue(typeof(T).ToString(), out provider) ? ((GenericProvider<T>)provider).Save(entity, saveChanges, detectChanges) : null;
            }
            else
            {
                var provider = new GenericProvider<T>(IsOffline);
                _providers.Add(typeof(T).ToString(), provider);
                objReturn = provider.Save(entity, saveChanges, detectChanges);
            }

            if (logEvent)
            {
                NotificationService.SaveNotification(logMessage, logNotification);
            }

            return objReturn;
        }

        public int SaveChanges<T>() where T : BaseEntity
        {
            if (_providers.ContainsKey(typeof(T).ToString()))
            {
                dynamic provider;
                if (_providers.TryGetValue(typeof(T).ToString(), out provider))
                {
                    var number = ((GenericProvider<T>)provider).SaveChanges();
                    _providers.Remove(typeof (T).ToString());
                    return number;
                }
            }
            return 0;
        }

        public T Single<T>(Expression<Func<T, bool>> predicate, bool newContext = false) where T : BaseEntity
        {
            if (_providers.ContainsKey(typeof(T).ToString()) && !newContext)
            {
                dynamic provider;
                if (_providers.TryGetValue(typeof (T).ToString(), out provider))
                {
                    return ((GenericProvider<T>) provider).Single(predicate);
                }
                return null;
            }
            else
            {
                var provider = new GenericProvider<T>(IsOffline, newContext);
                if (!newContext)
                {
                    _providers.Remove(typeof (T).ToString());
                    _providers.Add(typeof (T).ToString(), provider);
                }
                return provider.Single(predicate);
            }
        }

        public IQueryable<T> Where<T>(Expression<Func<T, bool>> predicate, bool newContext = false) where T : BaseEntity
        {
            if (_providers.ContainsKey(typeof(T).ToString()) && !newContext)
            {
                dynamic provider;
                if (_providers.TryGetValue(typeof(T).ToString(), out provider))
                {
                    return ((GenericProvider<T>)provider).Where(predicate);
                }
                return null;
            }
            else
            {
                var provider = new GenericProvider<T>(IsOffline, newContext);
                if (!newContext)
                {
                    _providers.Remove(typeof (T).ToString());
                    _providers.Add(typeof (T).ToString(), provider);
                }
                return provider.Where(predicate);
            }
        }

        public void ClearProviders()
        {
            _providers.Clear();
        }
    }
}
